package com.zut.chat.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * 视频服务类
 * 用于获取随机视频URL
 */
@Slf4j
@Service
public class VideoService {

    private final WebClient webClient;

    @Autowired
    public VideoService(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder
                .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(1024 * 1024)) // 1MB
                .build();
    }

    /**
     * 获取随机视频URL
     *
     * @return 视频URL的Mono
     */
    public Mono<String> getRandomVideoUrl() {
        String apiUrl = "https://api.lolimi.cn/API/xjj/xjj.php";

        return webClient.get()
                .uri(apiUrl)
                .header(HttpHeaders.USER_AGENT, "Mozilla/5.0 (compatible)")
                .exchangeToMono(response -> {
                    if (response.statusCode().is3xxRedirection()) {
                        // 处理重定向，获取最终的视频URL
                        String finalUrl = response.headers().header("Location").stream()
                                .findFirst()
                                .orElse(apiUrl);
                        log.info("获取到视频URL: {}", finalUrl);
                        return Mono.just(finalUrl);
                    } else if (response.statusCode().is2xxSuccessful()) {
                        // 如果是200响应，获取当前请求的URL作为视频URL
                        String finalUrl = "";
                        log.info("获取到视频URL: {}", finalUrl);
                        return Mono.just(finalUrl);
                    } else {
                        log.error("获取视频失败，状态码: {}", response.statusCode());
                        return Mono.error(new RuntimeException("获取视频失败: " + response.statusCode()));
                    }
                })
                .timeout(Duration.ofSeconds(30))
                .doOnError(error -> log.error("获取视频URL时发生错误", error))
                .onErrorReturn(""); // 出错时返回空字符串
    }

    /**
     * 验证视频URL是否有效
     *
     * @param videoUrl 视频URL
     * @return 是否有效的Mono
     */
    public Mono<Boolean> validateVideoUrl(String videoUrl) {
        if (videoUrl == null || videoUrl.trim().isEmpty()) {
            return Mono.just(false);
        }

        return webClient.head()
                .uri(videoUrl)
                .header(HttpHeaders.USER_AGENT, "Mozilla/5.0 (compatible)")
                .exchangeToMono(response -> {
                    boolean isValid = response.statusCode().is2xxSuccessful() ||
                                    response.statusCode().is3xxRedirection();
                    log.debug("视频URL验证结果: {} - {}", videoUrl, isValid);
                    return Mono.just(isValid);
                })
                .timeout(Duration.ofSeconds(10))
                .onErrorReturn(false);
    }

    /**
     * 获取视频元数据信息
     *
     * @param videoUrl 视频URL
     * @return 视频信息的Mono
     */
    public Mono<VideoInfo> getVideoInfo(String videoUrl) {
        return webClient.head()
                .uri(videoUrl)
                .header(HttpHeaders.USER_AGENT, "Mozilla/5.0 (compatible)")
                .exchangeToMono(response -> {
                    if (response.statusCode().is2xxSuccessful() ||
                        response.statusCode().is3xxRedirection()) {

                        String contentType = response.headers().header(HttpHeaders.CONTENT_TYPE)
                                .stream().findFirst().orElse("video/mp4");

                        String contentLength = response.headers().header(HttpHeaders.CONTENT_LENGTH)
                                .stream().findFirst().orElse("0");

                        VideoInfo videoInfo = VideoInfo.builder()
                                .url(videoUrl)
                                .contentType(contentType)
                                .size(Long.parseLong(contentLength))
                                .build();

                        return Mono.just(videoInfo);
                    } else {
                        return Mono.error(new RuntimeException("无法获取视频信息"));
                    }
                })
                .timeout(Duration.ofSeconds(10))
                .onErrorReturn(VideoInfo.builder().url(videoUrl).build());
    }

    /**
     * 视频信息数据类
     */
    public static class VideoInfo {
        private String url;
        private String contentType;
        private Long size;
        private String title;

        public static VideoInfoBuilder builder() {
            return new VideoInfoBuilder();
        }

        public static class VideoInfoBuilder {
            private String url;
            private String contentType = "video/mp4";
            private Long size = 0L;
            private String title;

            public VideoInfoBuilder url(String url) {
                this.url = url;
                return this;
            }

            public VideoInfoBuilder contentType(String contentType) {
                this.contentType = contentType;
                return this;
            }

            public VideoInfoBuilder size(Long size) {
                this.size = size;
                return this;
            }

            public VideoInfoBuilder title(String title) {
                this.title = title;
                return this;
            }

            public VideoInfo build() {
                VideoInfo videoInfo = new VideoInfo();
                videoInfo.url = this.url;
                videoInfo.contentType = this.contentType;
                videoInfo.size = this.size;
                videoInfo.title = this.title;
                return videoInfo;
            }
        }

        // Getters
        public String getUrl() { return url; }
        public String getContentType() { return contentType; }
        public Long getSize() { return size; }
        public String getTitle() { return title; }
    }
}
